﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using AMM.Model;
using AMM.Model.Business;

namespace AMM.DataAccess.Business {
    public class CustomerRepository : BaseRepository<Customer> {

        private int _pageSize;

        public CustomerRepository(int pageSize) {
            this._pageSize = pageSize;
        }

        public Customer FetchCustomerById(int customerId) {
            using (var ctx = this.Context) {
                return ctx.Customers.Find(customerId);
            }
        }

        public void DeleteMultipleCustomer(params int[] customerIds) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        ctx.Customers.Where(x => customerIds.Contains(x.CustomerId)).ToList().ForEach(x => {
                            ctx.Customers.Remove(x);
                        });
                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public List<Customer> FetchCustomerList() {
            using (var ctx = this.Context) {
                return ctx.Customers.ToList();
            }
        }

       public List<Customer> FetchCustomerList(CustomerSearchModel searchModel, int pageIndex) {
            using (var ctx = this.Context) {
                var query = ctx.Customers.Where(x => !string.IsNullOrEmpty(x.Code));

                if (!string.IsNullOrEmpty(searchModel.Code)) {
                    query = query.Where(x => x.Code.Contains(searchModel.Code));
                }
                if (!string.IsNullOrEmpty(searchModel.Name)) {
                    query = query.Where(x => x.Name.Contains(searchModel.Name));
                }
                if (!string.IsNullOrEmpty(searchModel.Address)) {
                    query = query.Where(x => x.Address.Contains(searchModel.Address));
                }
                if (searchModel.IsEnabled.HasValue) {
                    query = query.Where(x => x.IsEnabled == searchModel.IsEnabled.Value);
                }

                searchModel.Records = query.Count();
                pageIndex = (pageIndex - 1) * this._pageSize > searchModel.Records ? 1 : pageIndex;

                return query.OrderBy(x => x.CustomerId).Skip((pageIndex - 1) * this._pageSize).Take(this._pageSize).ToList();
            }
        }
       
    }
}
